﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core.DS
{
    public static partial class problem
    {
        public static dynamic swapProblem(bool flags,int pid,int eid)
        {
            var sql = new Sql.SqlDataContext();
            var current = sql.DSProblem.FirstOrDefault(row => row.pid == pid && row.eid == eid);
            if (current == null) return new
            {
                success = false,
                message = "找不到当前DSProblem"
            };
            if (flags == true)
            {
                if (!sql.DSProblem.Any(row => row.pid < current.pid && row.eid == eid))
                    return new
                    {
                        success = true
                    };
                var max = (from mm in sql.DSProblem
                           where mm.pid < current.pid
                           orderby mm.pid descending
                           select mm).FirstOrDefault();
                current.pid ^= max.pid;
                max.pid ^= current.pid;
                current.pid ^= max.pid;
                sql.GoPidSwap(current.pid, max.pid, eid);
            }
            if (flags == false)
            {
                if (!sql.DSProblem.Any(row => row.pid > current.pid && row.eid == eid))
                    return new
                    {
                        success = true
                    };
                var min = (from mm in sql.DSProblem
                           where mm.pid > current.pid
                           orderby mm.pid
                           select mm).FirstOrDefault();
                current.pid ^= min.pid;
                min.pid ^= current.pid;
                current.pid ^= min.pid;
                sql.GoPidSwap(current.pid, min.pid, eid);
            }
            sql.SubmitChanges();
            return new
            {
                success = true
            };
        }
    }
}
